package com.noodles.mall.filter;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.util.Optional;

public class LoginFilter extends UsernamePasswordAuthenticationFilter {

    @Autowired
    private SessionRegistry sessionRegistry;

    @SneakyThrows
    @Override
    // 身份验证
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        System.out.println("LoginFilter: attemptAuthentication 开始");
        if (!"POST".equals(request.getMethod())) {
            // 不是post请求
            System.out.println("LoginFilter: attemptAuthentication 结束1");
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }

        if (request.getContentType().contains(MediaType.APPLICATION_JSON_VALUE)) {
            String body = StreamUtils.copyToString(request.getInputStream(), StandardCharsets.UTF_8);
            String username = null, password = null;
            if (StringUtils.hasText(body)) {
                JSONObject jsonObject = JSONUtil.parseObj(body);
                username = Optional.ofNullable(jsonObject.get("username").toString()).orElse("").trim();
                password = Optional.ofNullable(jsonObject.get("password").toString()).orElse("").trim();
            }
            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
                    username, password);
            sessionRegistry.registerNewSession(request.getSession(true).getId(), username);
            System.out.println("LoginFilter: attemptAuthentication 结束2");
            return this.getAuthenticationManager().authenticate(authRequest);
        } else {
            System.out.println("LoginFilter: attemptAuthentication 结束3");
            return super.attemptAuthentication(request, response);
        }
    }
}
